package com.eling.elcms.basedoc.webapp.controller;

import com.eling.elcms.basedoc.model.DataStorage;
import com.eling.elcms.core.service.IGenericModelService;
import com.eling.elcms.core.webapp.controller.BaseFormController;
import com.eling.elcms.core.webapp.controller.Msg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("/api/datastorage")
public class DataStorageController extends BaseFormController {
	@Autowired
	private IGenericModelService gms;

	@RequestMapping(value = "/save", method = RequestMethod.POST)
	@ResponseBody
	public Msg save(@RequestParam String type, @RequestParam String key, @RequestParam String value) {
		DataStorage old = queryDs(type, key);
		DataStorage newDs = new DataStorage();
		if (null == old) {
			newDs = new DataStorage();
			newDs.setType(type);
			newDs.setKey(key);
		} else {
			newDs = old;
		}
		newDs.setValue(value);
		gms.save(newDs);
		return new Msg("保存成功");
	}

	@RequestMapping(value = "/queryvalue", method = RequestMethod.GET)
	@ResponseBody
	public String queryValue(@RequestParam String type, @RequestParam String key) {
		DataStorage ds = queryDs(type, key);
		return null == ds ? null : ds.getValue();
	}

	@RequestMapping(value = "/remove", method = RequestMethod.GET)
	@ResponseBody
	public String remove(@RequestParam String type, @RequestParam String key) {
		DataStorage ds = queryDs(type, key);
		if (null != ds) {
			gms.remove(ds);
		}
		return null == ds ? null : ds.getValue();
	}

	private DataStorage queryDs(String type, String key) {
		DataStorage cond = new DataStorage();
		cond.setType(type);
		cond.setKey(key);
		List<DataStorage> dss = gms.query(cond, DataStorage.class);
		return dss.isEmpty() ? null : dss.get(0);
	}
}
